iT邦幫忙

2022 iThome 鐵人賽

DAY 8
0
Modern Web

clojure 刷刷鍋系列 第 8

Clojure 肉片 -第 8 塊

  • 分享至 

  • xImage
  •  

【心得】

  1. 終於爬到 7kyu!
  2. best practice 第一種寫法 (apply map + [[10 0] [3 5] [5 8]]) 會做成 (map + [10 0] [3 5] [5 8]) 發現 map 除了常見的 (map f coll) 將 coll 分別丟進 fuction 執行後結果放進 list,其實還有 (map f c1 c2) 接收兩個 coll 的做法,用途是可以做到 parallel execution,對於這次的解題非常有用(下面舉個例子)
;; 會將兩個 vector 相同 index 值相加 1 + 2, 2 + 3, 3 + 4
(map + [1 2 3] [2 3 4]) => (3 5 7)

【今日湯底】

There is a bus moving in the city, and it takes and drop some people in each bus stop.

You are provided with a list (or array) of integer pairs. Elements of each pair represent number of people get into bus (The first item) and number of people get off the bus (The second item) in a bus stop.

Your task is to return number of people who are still in the bus after the last bus station (after the last array). Even though it is the last bus stop, the bus is not empty and some people are still in the bus, and they are probably sleeping there :D

Take a look on the test cases.

Please keep in mind that the test cases ensure that the number of people in the bus is always >= 0. So the return integer can't be negative.

The second value in the first integer array is 0, since the bus is empty in the first bus stop.

(必須通過以下測試)

(ns kata.bus-testing
  (:require [clojure.test :refer :all])
  (:use [kata.bus :rename {number solution}]))

(deftest basic-tests
  (is (= 5 (solution [[10 0] [3 5] [5 8]])))
  (is (= 17 (solution [[3 0] [9 1] [4 10] [12 2] [6 1] [7 10]])))
  (is (= 21 (solution [[3 0] [9 1] [4 8] [12 2] [6 1] [7 8]]))))

【我的答案】

(ns kata.bus)
(defn number
  [bus-stops]
  (reduce + (map #(- (first %) (second %)) bus-stops))
  )

思路:

  1. map 可以把 vector of vector 一個個拿出來
  2. 透過匿名函式再把每個 first and second 值相減
  3. 因為 map 後會是 list ex. (1 2 3),不能直接 + 借助了 reduce 處理單一 coll 的效果

【其他人的答案】

(ns kata.bus)
(defn number
  [bus-stops]
  (reduce - (apply map + bus-stops))
)
(ns kata.bus)
(defn number
  [bus-stops]
  (reduce + (map #(reduce - %) bus-stops)))

上一篇
Clojure 肉片 -第 7 塊
下一篇
Clojure 肉片 -第 9 塊
系列文
clojure 刷刷鍋30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言